<?php

// no direct access

defined( '_JEXEC' ) or die( 'Restricted access' );

jimport( 'joomla.application.component.view');

class ShopViewCategory extends JView
{
    function display($tpl = null)
    {
        $mtime = microtime();
        //Разделяем секунды и миллисекунды
        $mtime = explode(" ",$mtime);
        //Составляем одно число из секунд и миллисекунд
        $mtime = $mtime[1] + $mtime[0];
        //Записываем стартовое время в переменную
        $tstart = $mtime;
		
        $cat_id = (int)JRequest::getInt('id',0); // колучаем номер категории
        //printu($cat_id,'cat_id');
        $this->assignRef('cat_id',$cat_id);
        //  $model =& $this->getModel();
        //  $items = $model->getItemsList($category);
        $db =& JFactory::getDBO();
        $page = JRequest::getInt('page',1); // получаем номер страницы
        $ordering = JRequest::getVar('order_by',''); // получаем номер страницы

        $page_i = JRequest::getVar('page','');
        //	echo $page_i;
        $this->assignRef('page',$page_i);
        $this->assignRef('page_i',$page);
        if($page >0)
            $limit = "LIMIT ".(($page-1)*10).",10";
        else
            if($cat_id != 0)
                    $limit = "";
            else
                    $limit = "LIMIT 0,10";
        //setcookie('testcookie','its_workin'); // проверка на работоспособность cookie на машине клиента

        switch ($ordering){
            case 'price_d':
                    $order_by = 'ORDER BY price DESC, sklad_sum DESC';
            break;
            case 'price_a':
                    $order_by = "ORDER BY price ASC, sklad_sum DESC";
            break;
            default:
                    $order_by ='ORDER BY sklad_sum DESC, id ASC';
            break;
        }
        $query = "SELECT * FROM #__shop_categories WHERE id=$cat_id AND published=1";
        $db->setQuery($query);
        $category = $db->loadObject();
        //printu($category,'$category');
		
        if(is_object($category) || $cat_id == 0 )
        {
            $document	=& JFactory::getDocument();
            if($cat_id != 0){
                $query = "SELECT id FROM #__shop_prod
                    WHERE  price>'0' AND (cat_id=".$cat_id." OR dublicated_cat= ".$cat_id.") AND
                        published='1' AND main_img != ''";
                if($category->metatitle != '')
                    $document->setTitle($category->metatitle);
                else
                    $document->setTitle($category->name);
                if ($category->metadesc) {
                    $document->setDescription( $category->metadesc );
                }
                if ($category->metakey) {
                    $document->setMetadata('keywords', $category->metakey);
                }
                if($category->metadata){
                    $document->setMetadata('robots', $category->metadata);
                }
            }
            else{
                $query = "SELECT id FROM #__shop_prod
                    WHERE  price>'0'  AND published='1' AND main_img != '' AND cat_id>0";
                $document->setTitle('Все модели эротичного белья'); // устанавливаем заголовок страницу
            }
            $db->setQuery($query);
            $db->query();
            $count_all = $db->getNumRows(); // получаем количество всех товаров
            $this->assignRef('count',$count_all);

            $all_pages= ceil($count_all/10);

            $navig = "";
            if($page > 1 && $all_pages>=2){
                $navig .= "<a href=\"index.php?option=com_shop&view=category&id=".$cat_id."&page=".($page-1);
                if($order_by != '')
                        $navig.= "&order_by=".$ordering;
                $navig.= "\"><<</a> | ";
            }
            for($i=1;$i<=$all_pages;$i++){ // СОЗДАЕМ НАВИГАЦИОННУЮ ПАНЕЛЬ

                if($page != $i){
                    $navig .= "<a href=\"index.php?option=com_shop&view=category&id=".$cat_id."&page=".$i;
                    if($order_by != '')
                            $navig.= "&order_by=".$ordering;
                    $navig.= "\">".$i."</a>";
                }
                else
                    $navig .= $i;
                if($i != $all_pages)
                    $navig.= " | ";
            }
            if($page < $all_pages && $all_pages>=2){
                $navig .= " | <a href=\"index.php?option=com_shop&view=category&id=".$cat_id."&page=".($page+1);
                if($order_by != '')
                        $navig.= "&order_by=".$ordering;
                $navig.= "\">>></a>";
            }
			
            $this->assignRef('navig_panel',$navig);

            if($cat_id != 0){
                $query = "SELECT articul_wo_char,articul,name,price,old_price,id,main_img,sklad_sum,from_xml
                    FROM #__shop_prod
                    WHERE  price>0 AND (cat_id=".$cat_id." OR dublicated_cat= ".$cat_id.") AND
                        main_img != '' AND published='1' ".$order_by." ".$limit;
                if($limit != ""){
                    $navig.=" <b><a href=\"index.php?option=com_shop&view=category&id=".$cat_id."&page=0";
                    if($order_by != '')
                            $navig.= "&order_by=".$ordering;
                    $navig.= "\">Показать все товары</a></b>";
                }
                else{
                    $navig.=" <b>Показать все товары</b>";
                }
            }
            else{
                $query = "SELECT articul_wo_char,articul,name,price,old_price,id,main_img,sklad_sum,from_xml
                    FROM #__shop_prod
                    WHERE  price>0 AND main_img != '' AND published='1' ".$order_by." ".$limit;

            }
            //	echo $query;
            $db->setQuery($query);
            $items = $db->loadObjectList();

            $ids = array();
            foreach($items as $item){
                $ids[]= $item->id;
            }
            $ids = implode(',',$ids);
            if($ids != ''){
                $query = "SELECT * FROM #__shop_fields_values
                    WHERE sklad>0 AND field_id=1 AND object_id IN (".$ids.")"; // получаем все типы
                $db->setQuery($query);
                $types = $db->loadObjectList();
            }
            else
                $types = array();
            // сопоставляем все типы с товарами
            $new_types = array();
            foreach($items as $key=>$item){
                foreach($types as $key_two=>$type){
                    if($type->object_id == $item->id){
                        $new_types[$key][] = $type;
                        //unset($types[$key_two]);

                    }
                }
            }
			
            $this->assignRef('types',$new_types);
            $Itemid = (int)JRequest::getVar('Itemid');

            $uri = &JRequest::getURI() ; // url текущей ссылки
            setcookie('uri',$uri); //
            $session = &JFactory::getSession();
            $session->set('uri',$uri);

            $this->assignRef('sort',$ordering);
            $this->assignRef('category',$category);
            $this->assignRef('items',$items);
            $this->assignRef( 'Itemid',$Itemid);

            $mtime = microtime();
            $mtime = explode(" ",$mtime);
            $mtime = $mtime[1] + $mtime[0];
            //Записываем время окончания в другую переменную
            $tend = $mtime;
            //Вычисляем разницу
            $totaltime = ($tend - $tstart);
            //Выводим не экран
    //	echo "<br/><br/>Страница сгенерирована за $totaltime секунд !";
    //	echo "<br/> Peak memory usage: " . (memory_get_peak_usage(true) / 1024 / 1024) . " MB\r\n";
        }
        parent::display($tpl);
    }
}